//
//  WYCShimingController.m
//  掌上还
//
//  Created by 中企互联 on 2018/1/10.
//  Copyright © 2018年 中企互联. All rights reserved.
//

#import "WYCShimingController.h"
#import "configuration.h"
#import "WYCPhotographController.h"
#import "WQCMybankViewController.h"
@interface WYCShimingController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
/** 列表*/
@property(nonatomic,strong)UITableView *tableView;
/** 正面按钮*/
@property(nonatomic,strong)UIButton *idButton;

/** 身份证反面按钮*/
@property(nonatomic,strong)UIButton *idsideButton;
@property(nonatomic,strong)UIButton *shouButton;

/** 姓名*/
@property(nonatomic,strong)UITextField * name;
/**签发机关*/
@property(nonatomic,strong)NSString * address;
/** 身份证号*/
@property(nonatomic,strong)UITextField * num;
/** 民族*/
@property(nonatomic,strong)NSString * nationality;
/** 出生日期*/
@property(nonatomic,strong)NSString  *birth;
/** 性别*/
@property(nonatomic,strong)NSString  *sex;
/** 有效期限*/
@property(nonatomic,strong)UITextField  *Date;
/** 有效期限*/
@property(nonatomic,strong)UITextField  *issue;
@property(nonatomic,strong)NSString  *endDate;
@property(nonatomic,strong)NSString  *startDate;
@property(nonatomic,strong)NSString * faceUrl;
@property(nonatomic,strong)NSString * backUrl;

@property(nonatomic,strong)NSString * shouUrl;
@property(nonatomic,strong)NSString * shenfen;
@property(nonatomic,strong)NSString * issuestr;
@property(nonatomic,strong)NSString * nameStr;
@property(nonatomic,strong)NSString * numStr;
@property(nonatomic,strong)NSString * issueStr;
@property(nonatomic,strong)NSString * dateStr;



@property(nonatomic,strong)UIImageView * photoImage;

@property(nonatomic,strong)NSString * imgStr;
@property(nonatomic,strong)UIView * bgView;
@property (nonatomic,strong)NSArray *titArr;
@property (nonatomic,strong)NSMutableArray *dataArray;


@end

@implementation WYCShimingController

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray=@[@"",@"",@"",@""].mutableCopy;
    }
    return _dataArray;
}
-(NSArray *)titArr
{
    if (!_titArr) {
        _titArr= @[@"真实姓名",@"身份证号",@"签发机关",@"有效期限"];
    }
    return _titArr;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = NO;
    self.view.backgroundColor = WYCGlobalBg;
    self.navigationItem.title = @"实名认证";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"提交" target:self action:@selector(loginButtonClick)];


    _bgView = [[UIView alloc]init];
    _bgView.backgroundColor =wycMain;
    _bgView.frame = CGRectMake(0, 0, ScreenWidth, 400);
    _bgView.userInteractionEnabled =YES;
    UILabel *label= [MyUIClass makeUILabelWithFrame:CGRectMake(0, 23, ScreenWidth, 20) andBackColor:[UIColor clearColor] andText:@"请拍摄并上传本人身份证，完善身份信息" andTextColor:[UIColor whiteColor] andFont:[UIFont systemFontOfSize:14] andAlignment:NSTextAlignmentCenter];
    [_bgView addSubview:label];
    
    //身份证正面
    UIButton * IDButton = [[UIButton alloc] init];
    IDButton.frame = CGRectMake(20, label.frame.size.height+label.frame.origin.y+23, ScreenWidth/2-40, 100);
    [IDButton addTarget:self action:@selector(IDButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [IDButton setImage:[UIImage imageNamed:@"zhengm"] forState:UIControlStateNormal];
    [_bgView addSubview:IDButton];
    self.idButton = IDButton;
    
    //身份证反面
    UIButton * sideIDButton = [[UIButton alloc] init];
    sideIDButton.frame = CGRectMake(ScreenWidth/2+16, IDButton.y, ScreenWidth/2-40, 100);
    [sideIDButton addTarget:self action:@selector(sideButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [sideIDButton setImage:[UIImage imageNamed:@"zhengm"] forState:UIControlStateNormal];
    [_bgView addSubview:sideIDButton];
    self.idsideButton = sideIDButton;
    //手持身份证
    UIImageView * photoImageView = [[UIImageView alloc] init];
    photoImageView.frame = CGRectMake(20, IDButton.y+150,ScreenWidth-40, 130);
    photoImageView.image = [UIImage imageNamed:@"shouchi"];
    [photoImageView setUserInteractionEnabled:YES];
    [photoImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shouButtonClick)]];
    [_bgView addSubview:photoImageView];
    self.photoImage = photoImageView;
    
    
    UILabel  *lbZheng = [MyUIClass makeUILabelWithFrame:CGRectMake(0, IDButton.frame.size.height+IDButton.frame.origin.y+16, ScreenWidth/2, 20) andBackColor:[UIColor clearColor] andText:@"身份证正面" andTextColor:[UIColor whiteColor] andFont:[UIFont systemFontOfSize:14] andAlignment:NSTextAlignmentCenter];
    [_bgView  addSubview:lbZheng];
    UILabel  *lbfan = [MyUIClass makeUILabelWithFrame:CGRectMake(ScreenWidth/2, lbZheng.y, ScreenWidth/2, 20) andBackColor:[UIColor clearColor] andText:@"身份证反面" andTextColor:[UIColor whiteColor] andFont:[UIFont systemFontOfSize:14] andAlignment:NSTextAlignmentCenter];
    [_bgView  addSubview:lbfan];
    
    UILabel  *lbshou = [MyUIClass makeUILabelWithFrame:CGRectMake(0, photoImageView.frame.size.height+photoImageView.frame.origin.y+16, ScreenWidth, 20) andBackColor:[UIColor clearColor] andText:@"手持身份证" andTextColor:[UIColor whiteColor] andFont:[UIFont systemFontOfSize:14] andAlignment:NSTextAlignmentCenter];
    [_bgView  addSubview:lbshou];

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableView.backgroundColor = WYCGlobalBg;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.scrollEnabled = YES;
    self.tableView.tableHeaderView =_bgView;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"123"];
}

-(void)loginButtonClick
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
    [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色
    NSString  *name =self.dataArray[0];
    NSString  *num =self.dataArray[1];
    NSString  *issue =self.dataArray[2];
    NSString  *data =self.dataArray[3];
    NSLog(@"%@-%@-%@-%@",name,num,issue,data);
    if( name.length== 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"姓名不能为空"];
        return;
    }
   else if(num.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"身份证不能为空"];
        return;
    }
    else if(issue.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"签发机关不能为空"];
        return;
    }
   else if(data.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"有效期不能为空"];
        return;
    }
   else if(self.shouUrl.length == 0)
   {
       [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"手持身份证不能为空"];
       return;
   }
    else
    {
    WQCMybankViewController  *bankView = [[WQCMybankViewController alloc]init];
    bankView.name = name;
    bankView.address = self.address;
    bankView.num =num;
    bankView.nationality = self.nationality;
    bankView.sex =self.sex;
    bankView.issue = issue;
    bankView.birth= self.birth;
    bankView.endDate =self.endDate;
    bankView.startDate = self.startDate;
    bankView.shouchiUrl=_shouUrl;
    bankView.faceUrl = self.faceUrl;
    bankView.backUrl = self.backUrl;
    [self.navigationController pushViewController:bankView animated:YES];

    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 50;
    
}
-(void)shouButtonClick
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    picker.allowsEditing = YES;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];

}
//选取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *image1=[info objectForKey:UIImagePickerControllerEditedImage];
    self.photoImage.image = image1;
    //图片压缩
    NSData * data = UIImageJPEGRepresentation(image1, 0.3);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    [self loadImageUpdate:encodedImageStr];

    //选取完图片之后关闭视图
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.tableFooterView = [[UIView alloc] init];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"123" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    UILabel  *titLb = [MyUIClass makeUILabelWithFrame:CGRectMake(10, 15, 120, 20) andBackColor:[UIColor clearColor] andText:[self.titArr objectAtIndex:indexPath.row] andTextColor:[UIColor blackColor] andFont:[UIFont systemFontOfSize:14] andAlignment:NSTextAlignmentLeft];
    [cell.contentView addSubview:titLb];
    
        UITextField * codeTextField = [[UITextField alloc] init];
        codeTextField.frame = CGRectMake( 100,15,  250, 20);
        codeTextField.backgroundColor = [UIColor clearColor];
        codeTextField.tintColor = wycMain;
        codeTextField.text = [_dataArray objectAtIndex:indexPath.row];
    if (codeTextField.text.length) {
        codeTextField.enabled=YES;
    }else{
        codeTextField.enabled=NO;
    }
        codeTextField.tag=indexPath.row;
        codeTextField.delegate=self;
        codeTextField.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:codeTextField];


    return cell;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.dataArray replaceObjectAtIndex:textField.tag withObject:textField.text];
}




-(void)loadImageUpdate:(NSString *)img
{
    [SVProgressHUD showWithStatus:@"上传中..."];

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"base64Img"] = img;
    NSLog(@"%@",params);
    [HttpTool POST:updateImage params:params success:^(NSURLSessionDataTask *task, id responseObject)
     {
         if ([[responseObject objectForKey:@"code"] intValue] == 0)
         {
            NSString *shouurl = [responseObject objectForKey:@"result"];
             self.shouUrl =shouurl;
             NSLog(@"手持%@ %@",responseObject,_shouUrl);
             NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
             [defaults setObject:shouurl forKey:@"firstName"];
             [defaults synchronize];
             
             [self.tableView reloadData];
             [SVProgressHUD dismiss];

             [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"上传成功"];

             [SVProgressHUD dismiss];


         }else{
             [SVProgressHUD dismiss];
            self.photoImage.image = [UIImage imageNamed:@"shouchi"];
             [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
             [SVProgressHUD dismiss];

         }

     } fail:^(NSURLSessionDataTask *task, NSError *error)
     {             [SVProgressHUD dismiss];
         self.photoImage.image = [UIImage imageNamed:@"shouchi"];
         [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
         [SVProgressHUD dismiss];

     }];
    
}
-(void)loadZhengmian
{
    [SVProgressHUD showWithStatus:@"扫描中..."];
    //图片压缩
    NSData * data = UIImageJPEGRepresentation(_idButton.imageView.image, 1);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
            params[@"base64Img"] = encodedImageStr;
                 params[@"side"] = @"1";
    [HttpTool POST:ocridcard params:params success:^(NSURLSessionDataTask *task, id responseObject)
    {
    if ([[responseObject objectForKey:@"code"] intValue] == 0)
    {
        
        NSLog(@"%@",responseObject);
        NSDictionary * dict = [responseObject objectForKey:@"result"];
        //名字
//        _nameStr = [dict objectForKey:@"name"];
        //身份证号
//        _numStr = [dict objectForKey:@"num"];
//        _shenfen =[dict objectForKey:@"num"];
        _birth = [dict objectForKey:@"birth"];
        _address = [dict objectForKey:@"address"];
        _nationality = [dict objectForKey:@"nationality"];
        _sex = [dict objectForKey:@"sex"];
        
        _faceUrl =[dict objectForKey:@"faceUrl"];
         [self.dataArray replaceObjectAtIndex:0 withObject:[dict objectForKey:@"name"]];
         [self.dataArray replaceObjectAtIndex:1 withObject:[dict objectForKey:@"num"]];
        //[self.dataArray addObject:[dict objectForKey:@"num"]];

        [self.tableView reloadData];
        [SVProgressHUD dismiss];


    }else{
    
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error)
 {
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
        }];
    [SVProgressHUD dismiss];

}
-(void)loadfan
{
    [SVProgressHUD showWithStatus:@"扫描中..."];

        NSData * data = UIImageJPEGRepresentation(_idsideButton.imageView.image, 1);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
            params[@"base64Img"] = encodedImageStr;
            params[@"side"] = @"2";
            [HttpTool POST:ocridcard params:params success:^(NSURLSessionDataTask *task, id responseObject) {
                NSLog(@"反面%@",responseObject);
                [SVProgressHUD dismiss];
                if ([[responseObject objectForKey:@"code"] intValue] == 0) {
    
            NSDictionary * dict = [responseObject objectForKey:@"result"];
                    _dateStr = [NSString stringWithFormat:@"%@ - %@",[dict objectForKey:@"startDate"],[dict objectForKey:@"endDate"]];
                    self.startDate=[dict objectForKey:@"startDate"];
                    self.endDate = [dict objectForKey:@"endDate"];
                           _issueStr = [dict objectForKey:@"issue"];
//                    _issuestr =[dict objectForKey:@"issue"];
                    _backUrl =[dict objectForKey:@"backUrl"];
                    
                    [self.dataArray replaceObjectAtIndex:2 withObject:[dict objectForKey:@"issue"]];
                    [self.dataArray replaceObjectAtIndex:3 withObject:_dateStr];
                    
                  //  [self.dataArray addObject:[dict objectForKey:@"issue"]];
                  //  [self.dataArray addObject:_dateStr];

                    [self.tableView reloadData];


                                         }else{
    
                                              [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
                                             [SVProgressHUD dismiss];

                                          }
                                      } fail:^(NSURLSessionDataTask *task, NSError *error) {
                                          [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
                                          [SVProgressHUD dismiss];

                                      }];

}
#pragma make -------->>身份证正面
- (void)IDButtonClick{
    
    
    WYCPhotographController * photo = [[WYCPhotographController alloc] init];
    __weak __typeof(self) weakSelf = self;

    photo.updateUserImage =  ^(UIImage *image){
        [weakSelf.idButton setImage:image forState:UIControlStateNormal];
        [weakSelf loadZhengmian];
    };
   [self presentViewController:photo animated:NO completion:nil];
    
}

#pragma mark --------->>身份证反面
- (void)sideButtonClick
{
        WYCPhotographController * photo = [[WYCPhotographController alloc] init];
    __weak __typeof(self) weakSelf = self;
        photo.updateUserImage =  ^(UIImage *image)
       {
            [weakSelf.idsideButton setImage:image forState:UIControlStateNormal];
           [weakSelf loadfan];
        };
        [self presentViewController:photo animated:NO completion:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    
    
}
@end
